package com.md.youyouhui.ui.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.md.youyouhui.R;
import com.md.youyouhui.common.RecyclerViewSpacesItemDecoration;
import com.md.youyouhui.databinding.AdapterHomeGoodsBinding;
import com.md.youyouhui.databinding.AdapterVipPayBinding;
import com.md.youyouhui.databinding.FragmentHomeBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.net.NetWorkConstant;
import com.md.youyouhui.net.response.GetHomeMealNewResponse;
import com.md.youyouhui.net.response.GetLimitSellResponse;
import com.md.youyouhui.net.response.IndexResponse;
import com.md.youyouhui.net.response.QuestionResponse;
import com.md.youyouhui.ui.BaseFragment;
import com.md.youyouhui.ui.adapter.DataBoundViewHolder;
import com.md.youyouhui.ui.adapter.HomeMealAdapter;
import com.md.youyouhui.ui.adapter.HomeShoppingAdapter;
import com.md.youyouhui.ui.home.BannerShareActivity;
import com.md.youyouhui.ui.home.BannerViewActivity;
import com.md.youyouhui.ui.home.DirectPayActivity;
import com.md.youyouhui.ui.home.ReceiveOilActivity;
import com.md.youyouhui.ui.home.WebNewsActivity;
import com.md.youyouhui.ui.shopping.ShoppingMoreActivity;
import com.md.youyouhui.utils.GlideImageLoader;
import com.md.youyouhui.utils.SharedPreferencesUtils;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by AdministratorZJ
 * on 2019/4/4.
 */
public class HomeFragment extends BaseFragment {
    private FragmentHomeBinding homeBinding;
    private MainViewModel viewModel;
    private List<String> images = new ArrayList<>();
    private List<String> links = new ArrayList<>();
   // private int[] title = {R.drawable.youkachongzhi, R.drawable.lingquyouka, R.drawable.taocanchongzhi};
    //private String[] name = {"油卡直充", "领取油卡", "套餐充值"};


    private String[] nameGoods = {"家居百货","汽车用品","新手福利","邀请有礼"};
    private int[] imgGoods = {R.drawable.jiajubaihuo,R.drawable.qicheyongpin,R.drawable.jinkouyinliao,R.drawable.meiweilingshi};
    String[] name;
    int[] title;
    private List<String> stringList = new ArrayList<>();
    private HomeShoppingAdapter shoppingAdapter;
    private HomeMealAdapter mealAdapter;
    int widths;
    String show ;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        homeBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
        show = SharedPreferencesUtils.getString(mActivity, Constants.IS_SHOW, "");
        if("0".equals(show)){
            homeBinding.shoppingTitle2.setVisibility(View.GONE);
            homeBinding.glOilRedirect.setVisibility(View.GONE);
            homeBinding.line2.setVisibility(View.GONE);

            name = new String[]{"新手福利", "邀请有礼"};
            title = new int[]{ R.drawable.xinshoufuli, R.drawable.yaoqingyouli};
            GridLayoutManager manager =new GridLayoutManager(getActivity(),2);
            homeBinding.homeRecycler.setLayoutManager(manager);

        }else{
            name = new String[]{"油卡直充", "领取油卡", "新手福利", "邀请有礼"};
            title = new int[]{R.drawable.youkazhichong, R.drawable.lingquyouka, R.drawable.xinshoufuli, R.drawable.yaoqingyouli};

        }
        viewModel = new MainViewModel();
        initData();


        return homeBinding.getRoot();
    }

    public void initData() {


        widths = mActivity.getWindowManager().getDefaultDisplay().getWidth();
        initViewPager();
        homeBinding.ivCoupon.setOnClickListener(v -> startActivity(new Intent(mActivity, WebNewsActivity.class).putExtra("url", NetWorkConstant.BASE_URL + "account/receive/reward/index")));
        homeBinding.ivShare.setOnClickListener(v -> startActivity(new Intent(mActivity, BannerShareActivity.class)));
       // homeBinding.homeRecycler.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
        homeBinding.homeRecycler.setAdapter(new MyAdapter());

        HashMap<String, Integer> goodsTypeSpacesMap = new HashMap<>();
        goodsTypeSpacesMap.put(RecyclerViewSpacesItemDecoration.LEFT_DECORATION,5);//左间距
        goodsTypeSpacesMap.put(RecyclerViewSpacesItemDecoration.TOP_DECORATION,5);//左间距


        homeBinding.homeGoodsTypeRecycler.setAdapter(new GoodsTypeAdapter());
        homeBinding.homeGoodsTypeRecycler.addItemDecoration(new RecyclerViewSpacesItemDecoration(goodsTypeSpacesMap));

        shoppingAdapter = new HomeShoppingAdapter(mActivity);
        homeBinding.homeShoppingRecycler.setAdapter(shoppingAdapter);
        mealAdapter=new HomeMealAdapter(mActivity);
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.LEFT_DECORATION,5);//左间距
        stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.TOP_DECORATION,5);//左间距
        homeBinding.homeMealRecycler.addItemDecoration(new RecyclerViewSpacesItemDecoration(stringIntegerHashMap));
        homeBinding.homeMealRecycler.setAdapter(mealAdapter);
        homeBinding.banner.setOnBannerListener(position -> {
            if ("share".equals(links.get(position))) {
                startActivity(new Intent(mActivity, BannerShareActivity.class));
            } else if ("security".equals(links.get(position))) {
                startActivity(new Intent(mActivity, BannerViewActivity.class).putExtra("imageId", R.drawable.banner_long));
            } else {
                startActivity(new Intent(mActivity, WebNewsActivity.class).putExtra("url", links.get(position)).putExtra("title", "详情"));
            }
        });
        homeBinding.ivRookie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, BannerViewActivity.class).putExtra("imageId", R.drawable.rookie_content));
            }
        });
        getHomeMeal();
        //getQuestionList();
        getNotice();
    }
    private void getNotice() {
        viewModel.getShoppingLimitSell().observe(this, listResource -> {
            assert listResource != null;
            switch (listResource.status) {
                case LOADING:
                    homeBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    homeBinding.progress.setVisibility(View.GONE);
                    List<GetLimitSellResponse> data = listResource.data;
                    if (null == data) {
                        return;
                    }
                    shoppingAdapter.upDate(data);
                    break;
                case ERROR:
                    homeBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(mActivity, listResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void showNotice() {
       /* homeBinding.marqueeView.startWithList(stringList);
        homeBinding.marqueeView.startFlipping();*/
    }

    private void getQuestionList() {
        viewModel.question(1, 2).observe(this, questionResponse -> {
            assert questionResponse != null;
            switch (questionResponse.status) {
                case SUCCESS:
                    QuestionResponse data = questionResponse.data;
                    if (null == data) {
                        return;
                    }
                    List<QuestionResponse.Rows> rows = data.rows;
                    break;
                case ERROR:
                    ToastUtils.errMake(mActivity, questionResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void getHomeMeal() {
        viewModel.getHomeMealNew().observe(this, homeNewsResponse -> {
            assert homeNewsResponse != null;
            switch (homeNewsResponse.status) {
                case LOADING:
                    break;
                case SUCCESS:
                    homeBinding.progress.setVisibility(View.GONE);
                    List<GetHomeMealNewResponse> data = homeNewsResponse.data;
                    if (null == data) {
                        return;
                    }
                    mealAdapter.upDate(data);
                    break;
                case ERROR:
                    homeBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(mActivity, homeNewsResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void initViewPager() {
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) homeBinding.banner.getLayoutParams();
        layoutParams.width = widths;
        layoutParams.height = (int) (widths / 1.8);
        homeBinding.banner.setLayoutParams(layoutParams);

        viewModel.index(1, 5).observe(this, listResource -> {
            assert listResource != null;
            switch (listResource.status) {
                case LOADING:
                    break;
                case SUCCESS:
                    IndexResponse data = listResource.data;
                    if (null == data) {
                        return;
                    }
                    for (int i = 0; i < data.rows.size(); i++) {
                        images.add(data.rows.get(i).cover);
                        links.add(data.rows.get(i).link);
                    }
                    showViewpage();
                    break;
                case ERROR:
                    ToastUtils.errMake(mActivity, listResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void showViewpage() {
        /*homeBinding.banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
        homeBinding.banner.setIndicatorGravity(BannerConfig.CENTER);*/
        homeBinding.banner.setDelayTime(3000);
        //设置图片源
        homeBinding.banner.setImages(images);
        homeBinding.banner.setImageLoader(new GlideImageLoader());
        //设置标题源
        //homeBinding.banner.setBannerTitles(titles);
        homeBinding.banner.start();
    }
    class GoodsTypeAdapter extends RecyclerView.Adapter<DataBoundViewHolder<AdapterHomeGoodsBinding>> {

        @NonNull
        @Override
        public DataBoundViewHolder<AdapterHomeGoodsBinding> onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            AdapterHomeGoodsBinding inflate = DataBindingUtil.inflate(LayoutInflater.from(mActivity), R.layout.adapter_home_goods, viewGroup, false);
            return new DataBoundViewHolder<>(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull DataBoundViewHolder<AdapterHomeGoodsBinding> holder, int i) {

            holder.binding.goodsImg.setImageResource(imgGoods[i]);
            holder.itemView.setOnClickListener(v -> {

                if (i == 0) {
                    startActivity(new Intent(mActivity, ShoppingMoreActivity.class)
                            .putExtra("title", "家居百货").putExtra("id", "8e47b2d76a964edebd47d2e6fb42b267"));
                } else if (i == 1) {
                    startActivity(new Intent(mActivity, ShoppingMoreActivity.class)
                            .putExtra("title", "汽车用品").putExtra("id", "17c09de8d3a84079a3210e125394cb38"));
                } else if (i == 2) {
                    startActivity(new Intent(mActivity, ShoppingMoreActivity.class)
                            .putExtra("title", "进口饮料").putExtra("id", "cb15f35ec7194171832f100afaabe4ca"));
                }
                else if (i == 3) {
                    startActivity(new Intent(mActivity, ShoppingMoreActivity.class)
                            .putExtra("title", "美味零食").putExtra("id","8ea72eac832a4e7e85562ab2e50c478e"));
                }

            });
        }

        @Override
        public int getItemCount() {
            return imgGoods.length;
        }
    }
    class MyAdapter extends RecyclerView.Adapter<DataBoundViewHolder<AdapterVipPayBinding>> {

        @NonNull
        @Override
        public DataBoundViewHolder<AdapterVipPayBinding> onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            AdapterVipPayBinding inflate = DataBindingUtil.inflate(LayoutInflater.from(mActivity), R.layout.adapter_vip_pay, viewGroup, false);
            return new DataBoundViewHolder<>(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull DataBoundViewHolder<AdapterVipPayBinding> holder, int i) {



            holder.binding.homePay.setImageResource(title[i]);
            holder.binding.homeName.setText(name[i]);


            holder.itemView.setOnClickListener(v -> {
                if (i == 0) {
                    startActivity(new Intent(mActivity, DirectPayActivity.class));
                } else if (i == 1) {
                    //http://youyida360.top:9512/api/account/receive/reward/index
                    startActivity(new Intent(mActivity, ReceiveOilActivity.class));
                } else if (i == 2) {
                    startActivity(new Intent(mActivity, WebNewsActivity.class).putExtra("url", NetWorkConstant.BASE_URL + "account/receive/reward/index"));
                }
                else if (i == 3) {
                    startActivity(new Intent(mActivity, BannerShareActivity.class));
                }

            });
        }

        @Override
        public int getItemCount() {

            return title.length;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //homeBinding.marqueeView.stopFlipping();
        homeBinding.banner.stopAutoPlay();
    }
}
